package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ArticleConfigMapper;
import com.heima.article.service.ArticleService;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.mess.ArticleVisitStreamMess;
import com.heima.model.mess.NewsUpOrDownMess;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-11-17 15:18
 */
@Component
@Slf4j
public class NewsListener {

    @Autowired
    private ArticleConfigMapper mapper;
    @Autowired
    private ArticleService articleService;

    @KafkaListener(topics = {WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC})
    public void upOrDown(String msg){
        //1.将字符串还原成对象
        NewsUpOrDownMess newsMsg = JSON.parseObject(msg, NewsUpOrDownMess.class);
        //2.给配置表修改值
        mapper.update(null, Wrappers.<ApArticleConfig>lambdaUpdate()
                .eq(ApArticleConfig::getArticleId,newsMsg.getArticleId())
                .set(ApArticleConfig::getIsDown,newsMsg.getEnable() == 0 ? 1 : 0)
        );
    }

    @KafkaListener(topics = {HotArticleConstants.HOT_ARTICLE_INCR_HANDLE_TOPIC})
    public void streamHotArticle(String msg){
        if(StringUtils.isNotBlank(msg)){
            ArticleVisitStreamMess mess = JSON.parseObject(msg, ArticleVisitStreamMess.class);
            articleService.updateArticleBehavior(mess);
        }

    }
}
